package com.charles.bigdata.mapreduce.joinuser;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class StepFirst {
	static class FirstMapper extends Mapper<LongWritable, Text, Text, Text> {
		@Override
		protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, Text>.Context context)
				throws IOException, InterruptedException {
			String line = value.toString();
			String[] arr = line.split(":");
			String user = arr[0];
			String friends = arr[1];
			for (String friend : friends.split(",")) {
				context.write(new Text(friend), new Text(user));
			}
		}
	}

	static class FirstReducer extends Reducer<Text, Text, Text, Text> {
		@Override
		protected void reduce(Text friend, Iterable<Text> users, Reducer<Text, Text, Text, Text>.Context context)
				throws IOException, InterruptedException {
			final StringBuffer buf = new StringBuffer("");
			for (Text user : users) {
				buf.append(user).append(",");
			}
			context.write(friend, new Text(buf.toString()));
		}
	}

	public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();
		Job job1 = Job.getInstance(conf);
		job1.setJarByClass(StepFirst.class);

		job1.setMapperClass(FirstMapper.class);
		job1.setReducerClass(FirstReducer.class);

		job1.setOutputKeyClass(Text.class);
		job1.setOutputValueClass(Text.class);

		FileInputFormat.setInputPaths(job1, new Path(args[0]));
		FileOutputFormat.setOutputPath(job1, new Path(args[1]));

		boolean res = job1.waitForCompletion(true);
		System.exit(res ? 0 : 1);
	}
}
